import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Toast } from 'vant'

const login = () => import('@/views/login')
const layout = () => import('@/views/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const video = () => import('@/views/video')
const mine = () => import('@/views/mine')
const UserEdit = () => import('@/views/mine/UserEdit')
const article = () => import('@/views/article')
const search = () => import('@/views/search')
const result = () => import('@/views/search/SearchResult')
const chat = () => import('@/views/mine/MyChat')

Vue.use(VueRouter)

const routes = [
  { path: '', redirect: '/layout/home' },
  { name: 'login', path: '/login', component: login },
  { name: 'UserEdit', path: '/mine/edit', component: UserEdit },
  { name: 'article', path: '/article/:id', component: article },
  { name: 'search', path: '/search', component: search },
  { name: 'result', path: '/search/result', component: result },
  { name: 'chat', path: '/mine/chat', component: chat },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      // 子路由不加`/`拼接父路由路径
      { name: 'home', path: 'home', component: home, meta: { needKeep: true } },
      { name: 'ask', path: 'ask', component: ask },
      { name: 'video', path: 'video', component: video },
      {
        name: 'mine',
        path: 'mine',
        component: mine,
        meta: {
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// to：   去哪（得到的是路由信息对象）
// from： 从哪来（得到的是路由信息对象）
// next： 是一个放行函数，调用它就代表放行，不调用代表不放行
//    next是一个函数，调用就代表放行，不调用代表不放行（空白）
//    next(false)也是代表不放行（留在原地）,next('路径') 放行到指定路径
//    this.$router.push({
//         name: 'login',
//         query: {}
//     })
//    $router.push能怎么用，next就能怎么用 --- next跳转时也可以携带参数
// 给路由打标记
router.beforeEach((to, from, next) => {
  // 是所有页面都要判断是否登录？
  if (to.meta.needLogin) {
    // 判断是否有这个标记，如果为true代表需要登录
    if (store.state.user.tokenObj.token) {
      // 有token代表登录了
      next()
    } else {
      Toast('请先登录')
      // 没登录
      next({
        name: 'login',
        query: {
          back: to.name
        }
      })
    }
  } else {
    // 代表不需要登录
    next()
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

export default router
